import * as vscode from 'vscode';
import * as child_process from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
const commandHandleArray: vscode.Disposable[] = [];
export function activate(context: vscode.ExtensionContext) {
    // 注册命令：在右键菜单和命令面板中可见
    let disposable = vscode.commands.registerCommand(
        'typora-opener.openWithTypora', 
        async (uri: vscode.Uri) => {
            try {
                // 获取当前选中的文件（支持资源管理器右键和编辑器右键）
                if (!uri) {
                    const editor = vscode.window.activeTextEditor;
                    if (!editor) {
                        vscode.window.showErrorMessage('未选中Markdown文件');
                        return;
                    }
                    uri = editor.document.uri;
                }

                // 验证文件类型是否为Markdown
                if (path.extname(uri.fsPath).toLowerCase() !== '.md') {
                    vscode.window.showErrorMessage('选中的文件不是Markdown文件(.md)');
                    return;
                }

                // 获取当前操作系统
                const platform = process.platform;
                let typoraPath: string | undefined;

                // 从配置中获取对应平台的Typora路径
                const config = vscode.workspace.getConfiguration('typora-opener.path');
                switch (platform) {
                    case 'win32':
                        typoraPath = config.get('windows');
                        break;
                    case 'darwin':
                        typoraPath = config.get('mac');
                        break;
                    case 'linux':
                        typoraPath = config.get('linux');
                        break;
                    default:
                        vscode.window.showErrorMessage(`不支持的操作系统: ${platform}`);
                        return;
                }

                // 验证Typora路径配置
                if (!typoraPath) {
                    vscode.window.showErrorMessage('未配置Typora路径，请在设置中配置');
                    return;
                }

                // 检查Typora可执行文件是否存在
                const resolvedTyporaPath = path.resolve(typoraPath);
                if (!fs.existsSync(resolvedTyporaPath)) {
                    const message = `未找到Typora程序，路径: ${resolvedTyporaPath}`;
                    const result = await vscode.window.showErrorMessage(
                        message, 
                        '打开设置'
                    );
                    if (result === '打开设置') {
                        vscode.commands.executeCommand(
                            'workbench.action.openSettings', 
                            'typora-opener.path'
                        );
                    }
                    return;
                }

                // 验证目标文件是否存在
                const filePath = uri.fsPath;
                if (!fs.existsSync(filePath)) {
                    vscode.window.showErrorMessage(`文件不存在: ${filePath}`);
                    return;
                }

                // 根据不同平台启动Typora
                if (platform === 'win32') {
                    // Windows平台特殊处理（解决中文路径和VS Code环境限制）
                    const absoluteTyporaPath = resolvedTyporaPath.replace(/\//g, '\\');
                    const absoluteFilePath = path.resolve(filePath).replace(/\//g, '\\');
                    const terminal = vscode.window.createTerminal({
                      name: "Typora",
                      hideFromUser: true,
                    });
                    terminal.sendText(`cmd /c start "${absoluteTyporaPath}" "${absoluteFilePath}"`);
                } 
                else if (platform === 'darwin' || platform === 'linux') {
                    // macOS和Linux平台处理
                    try {
                        child_process.execFile(typoraPath, [filePath], (error) => {
                            if (error) {
                                vscode.window.showErrorMessage(
                                    `启动Typora失败: ${error.message}\n` +
                                    `路径: ${typoraPath}\n` +
                                    `文件: ${filePath}`
                                );
                            }
                        });
                    } catch (error) {
                        if (error instanceof Error) {
                            vscode.window.showErrorMessage(`执行错误: ${error.message}`);
                        }
                    }
                }

            } catch (error) {
                if (error instanceof Error) {
                    vscode.window.showErrorMessage(`操作失败: ${error.message}`);
                } else {
                    vscode.window.showErrorMessage(`发生未知错误: ${String(error)}`);
                }
            }
        }
    );

    commandHandleArray.push(disposable);
    context.subscriptions.push(disposable);
}
// 扩展卸载时执行（清理资源）
export function deactivate() {
  commandHandleArray.forEach((i) => {
    i.dispose();
  });
}